package com.company.aicrawlers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.aicrawlers.common.exception.BusinessException;
import com.company.aicrawlers.entity.CollectTask;
import com.company.aicrawlers.entity.CollectTaskPlatform;
import com.company.aicrawlers.entity.CollectTaskQuestion;
import com.company.aicrawlers.entity.Question;
import com.company.aicrawlers.mapper.CollectTaskMapper;
import com.company.aicrawlers.mapper.QuestionMapper;
import com.company.aicrawlers.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 采集任务 Service实现类
 * 
 * @author AI Crawlers
 * @since 2025-10-10
 */
@Slf4j
@Service
public class CollectTaskServiceImpl extends ServiceImpl<CollectTaskMapper, CollectTask> 
        implements CollectTaskService {

    @Autowired
    private CollectTaskPlatformService taskPlatformService;

    @Autowired
    private CollectTaskQuestionService taskQuestionService;

    @Autowired
    private CollectTaskQuestionPlatformService taskQuestionPlatformService;

    @Autowired
    private CollectResultService resultService;

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTask(String taskName, List<String> platforms, List<Long> questionIds, String remark) {
        log.info("创建采集任务: taskName={}, platforms={}, questionIds={}", taskName, platforms, questionIds);

        // 参数校验
        if (taskName == null || taskName.trim().isEmpty()) {
            throw new BusinessException("任务名称不能为空");
        }
        if (platforms == null || platforms.isEmpty()) {
            throw new BusinessException("平台列表不能为空");
        }
        if (questionIds == null || questionIds.isEmpty()) {
            throw new BusinessException("问句列表不能为空");
        }

        // 验证问句是否存在
        List<Question> questions = questionMapper.selectBatchIds(questionIds);
        if (questions.size() != questionIds.size()) {
            throw new BusinessException("部分问句不存在");
        }

        // Step 1: 创建任务
        CollectTask task = new CollectTask();
        task.setTaskName(taskName);
        task.setTotalQuestionCount(questionIds.size());
        task.setTotalPlatformCount(platforms.size());
        task.setTotalCollectCount(questionIds.size() * platforms.size());
        task.setTaskStatus("pending");
        task.setProgressCompleted(0);
        task.setProgressPercentage(BigDecimal.ZERO);
        task.setSuccessCount(0);
        task.setFailCount(0);
        task.setRemark(remark);
        task.setCreateTime(LocalDateTime.now());
        this.save(task);

        Long taskId = task.getTaskId();
        log.info("任务创建成功, taskId={}", taskId);

        // Step 2: 配置平台
        taskPlatformService.batchCreate(taskId, platforms, questionIds.size());

        // Step 3: 添加问句
        taskQuestionService.batchCreate(taskId, questionIds, platforms.size());

        // Step 4: 创建执行状态矩阵（问句×平台笛卡尔积）
        taskQuestionPlatformService.batchCreateMatrix(taskId, questionIds, platforms);

        log.info("任务创建完成, taskId={}, 共需采集{}次", taskId, task.getTotalCollectCount());
        return taskId;
    }

    @Override
    public IPage<CollectTask> getPageList(Page<CollectTask> page, String taskStatus) {
        LambdaQueryWrapper<CollectTask> wrapper = new LambdaQueryWrapper<>();
        if (taskStatus != null && !taskStatus.trim().isEmpty()) {
            wrapper.eq(CollectTask::getTaskStatus, taskStatus);
        }
        wrapper.orderByDesc(CollectTask::getCreateTime);
        return this.page(page, wrapper);
    }

    @Override
    public Map<String, Object> getTaskDetail(Long taskId) {
        // 获取任务基本信息
        CollectTask task = this.getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 获取平台列表
        List<CollectTaskPlatform> platforms = taskPlatformService.getByTaskId(taskId);

        // 获取问句列表
        List<CollectTaskQuestion> questions = taskQuestionService.getByTaskId(taskId);

        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("task", task);
        result.put("platforms", platforms);
        result.put("questions", questions);

        return result;
    }

    @Override
    public Map<String, Object> getPendingQuestions(Long taskId) {
        // 获取任务信息
        CollectTask task = this.getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 获取平台列表
        List<CollectTaskPlatform> platforms = taskPlatformService.getByTaskId(taskId);
        List<String> platformNames = new ArrayList<>();
        for (CollectTaskPlatform platform : platforms) {
            if (platform.getEnabled()) {
                platformNames.add(platform.getPlatformName());
            }
        }

        // 获取未完成的问句×平台组合
        List<Map<String, Object>> pendingList = taskQuestionPlatformService.getPendingByTask(taskId);

        // 按问句分组，计算每个问句待执行的平台
        Map<Long, Map<String, Object>> questionMap = new LinkedHashMap<>();
        for (Map<String, Object> item : pendingList) {
            Long questionId = (Long) item.get("questionId");
            String platformName = (String) item.get("platformName");

            if (!questionMap.containsKey(questionId)) {
                Map<String, Object> questionInfo = new HashMap<>();
                questionInfo.put("questionId", questionId);
                questionInfo.put("questionContent", item.get("questionContent"));
                questionInfo.put("executeStatus", item.get("executeStatus"));
                questionInfo.put("pendingPlatforms", new ArrayList<String>());
                questionMap.put(questionId, questionInfo);
            }

            @SuppressWarnings("unchecked")
            List<String> pendingPlatforms = (List<String>) questionMap.get(questionId).get("pendingPlatforms");
            pendingPlatforms.add(platformName);
        }

        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("taskId", taskId);
        result.put("taskName", task.getTaskName());
        result.put("platforms", platformNames);
        result.put("pendingQuestions", new ArrayList<>(questionMap.values()));
        result.put("totalPending", questionMap.size());

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelTask(Long taskId) {
        CollectTask task = this.getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        task.setTaskStatus("cancelled");
        task.setEndTime(LocalDateTime.now());
        this.updateById(task);

        log.info("任务已取消, taskId={}", taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTask(Long taskId) {
        CollectTask task = this.getById(taskId);
        if (task == null) {
            throw new BusinessException("任务不存在");
        }

        // 删除任务（级联删除由数据库外键处理，或手动删除）
        this.removeById(taskId);

        // 手动删除关联数据
        LambdaQueryWrapper<CollectTaskPlatform> platformWrapper = new LambdaQueryWrapper<>();
        platformWrapper.eq(CollectTaskPlatform::getTaskId, taskId);
        taskPlatformService.remove(platformWrapper);

        LambdaQueryWrapper<CollectTaskQuestion> questionWrapper = new LambdaQueryWrapper<>();
        questionWrapper.eq(CollectTaskQuestion::getTaskId, taskId);
        taskQuestionService.remove(questionWrapper);

        log.info("任务已删除, taskId={}", taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTaskProgress(Long taskId) {
        // 查询已完成的采集数
        LambdaQueryWrapper<CollectTaskQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CollectTaskQuestion::getTaskId, taskId);
        wrapper.eq(CollectTaskQuestion::getExecuteStatus, "completed");
        long completedCount = taskQuestionService.count(wrapper);

        CollectTask task = this.getById(taskId);
        if (task == null) {
            return;
        }

        // 计算百分比
        BigDecimal percentage = BigDecimal.ZERO;
        if (task.getTotalQuestionCount() > 0) {
            percentage = BigDecimal.valueOf(completedCount)
                    .multiply(BigDecimal.valueOf(100))
                    .divide(BigDecimal.valueOf(task.getTotalQuestionCount()), 2, RoundingMode.HALF_UP);
        }

        // 更新任务进度
        task.setProgressCompleted((int) completedCount);
        task.setProgressPercentage(percentage);

        // 检查是否全部完成
        if (completedCount == task.getTotalQuestionCount()) {
            task.setTaskStatus("completed");
            task.setEndTime(LocalDateTime.now());
            if (task.getStartTime() != null) {
                long duration = java.time.Duration.between(task.getStartTime(), task.getEndTime()).getSeconds();
                task.setDuration((int) duration);
            }
        } else if ("pending".equals(task.getTaskStatus()) && completedCount > 0) {
            task.setTaskStatus("running");
            task.setStartTime(LocalDateTime.now());
        }

        this.updateById(task);
        log.debug("任务进度已更新, taskId={}, progress={}/{}", taskId, completedCount, task.getTotalQuestionCount());
    }
}

